package LeetCode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @Author: Dijah
 * @Date: 2023/3/28 14:58
 * @Desc: https://leetcode.cn/problems/find-all-anagrams-in-a-string/
 */
public class code438_findAnagrams {
    public static List<Integer> findAnagrams(String s,String p){
        HashMap<Character,Integer> need = new HashMap<>();
        HashMap<Character,Integer> window = new HashMap<>();

        //将p中字符串放到need中
        for(int i = 0; i < p.length(); i++){
            char c = p.charAt(i);
            need.put(c,need.getOrDefault(c,0) + 1);
        }

        int left = 0;
        int right = 0;
        int valid =0;
        List<Integer> res = new ArrayList<>();
        while(right < s.length()){
            char c = s.charAt(right);
            right++;
            //扩充右侧窗口
            if(need.containsKey(c)){
                window.put(c,window.getOrDefault(c,0) + 1);
                if(need.get(c).equals(window.get(c))){
                    //value相等，要记录res
                    valid++;
                }
            }

            //是否需要收缩左侧窗口
            while(right - left >= p.length()){
                if(valid == need.size()){
                    res.add(left);
                }
                //收缩
                char d = s.charAt(left);
                left++;
                if(need.containsKey(d)){
                    if(need.get(d).equals(window.get(d))){
                        valid--;
                    }
                    window.put(d,window.getOrDefault(d,0) - 1);
                }
            }
        }
        return res;
    }

    public static void main(String[] args) {
        String s = "cbaebabacd";
        String p = "abc";
        List<Integer> anagrams = findAnagrams(s, p);
        System.out.println(anagrams.toString());
    }
}
